package com.wayin.lift.socket;

import com.wayin.lift.config.SpringUtils;
import com.wayin.lift.entity.PersonnelEntity;
import com.wayin.lift.service.PersonnelService;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import static java.lang.Thread.sleep;

public class Server_Andriod implements Runnable{

	@Autowired
	private PersonnelService personnelService;
	
	private static final int PORT = 8099;
	private static final String CHARSET = "UTF-8";
	public static List<Socket> sockets = new ArrayList<>();
	ServerSocket server = null;

	public Server_Andriod() {
		try {
			server = new ServerSocket(PORT);
			System.out.println("andirod客户端Socket服务启动成功~");
		} catch (IOException e) {
			System.out.println("初始化Socket服务异常:\n");
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			while (true) {
				// 建立socket接口,accept方法等到用户连接才会继续执行
				Socket socket = server.accept();
				socket.setKeepAlive(true);
				// 在服务器显示连接的电脑
				String message = socket.getInetAddress().getHostAddress().toString();
				System.out.println("android客户端：" + message + "已连接~");
				// 将已有的连接添加到集合中
				sockets.add(socket);

				// 建立读取客户端数据的线程
				Thread t = new Thread(new ReadClientDataThread(socket));
				t.start();

//				Thread test = new Thread(new test());
//				test.start();

				//创建读取监控socket的心跳
//				Thread thread=new Thread(new Socket_Task(socket,"andirod"));
//
//				thread.start();
			}
		} catch (Exception e) {
			System.out.println("Socket运行中出现了异常：\n");
			e.printStackTrace();
		}
	}

//	public class test implements Runnable{
//
//		@Override
//		public void run() {
//			try {
//				personnelService = SpringUtils.getBean("personnelService");
//				while (true) {
//					if (sockets.size() > 0) {
//						PersonnelEntity p = personnelService.getById(1);
//						SendMessageToClient("{\"openId\":\"" + p.getOpenId() + "\",\"picture\":\"" + p.getPicture() + "\",\"name\":\"" + p.getName() + "\"}");
//						sleep(3600);
//					} else {
//						return;
//					}
//				}
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//	}
	
	public static void SendMessageToClient(String message) {
		// 遍历集合,寻找已经链接的客户端
		for (Socket s : sockets) {
			// 判断是否已经连接
			System.out.println(message);
			try {
			    if (null != s && !s.isClosed()) {
					OutputStream os = s.getOutputStream();
					os.write(message.getBytes(CHARSET));
					os.flush();
			    } else {
			    	s.close();
					sockets.remove(s);
				}
			} catch (Exception e) {
				Socket_Task socket_task = new Socket_Task(s, "android");
				socket_task.run();
				System.gc();
//				sockets.remove(s);
				System.out.println("Socket服务向客户端发送数据出现了异常:\n");
				e.printStackTrace();
			}
		}
	}
	

}